/*
 * @Date: 2019-11-26 10:24:14
 * @名称: 全局方法
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2020-10-12 22:09:53
 */
import 'dart:convert';
import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pica_acg/AppSettings.dart';
import 'package:pica_acg/DataBaseFunction.dart';
import 'package:pica_acg/GlobalKey.dart';
import 'package:pica_acg/GlobalSettings.dart';
import 'package:common_utils/common_utils.dart';
import 'package:pica_acg/GlobalWidget.dart';
import 'package:pica_acg/tools/extends/Json/ComicsInfo/ComicsInfoListJson.dart'
    as comicsInfoListJson;
import 'package:random_string/random_string.dart';
import 'package:url_launcher/url_launcher.dart';

var $url = '';
/*
 * 获取服务器总数据
 */
String getServiceList() {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/ServiceList';
  } else {
    $url = $global_ServiceDomain_me + 'api/ServiceList';
  }
  return $url;
}

/*
 * 获取Banner总数据
 */
String getBannerList() {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/Banner';
  } else {
    $url = $global_ServiceDomain_back + 'api/Banner';
  }
  return $url;
}

/*
 * 获取公告总数据
 */
String getAnnouncementsList() {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/Announcements';
  } else {
    $url = $global_ServiceDomain_back + 'api/Announcements';
  }
  return $url;
}

/*
 * 大家都在搜索关键字
 */
String getCategoryEveryoneSearch() {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/CategoryEveryoneSearch';
  } else {
    $url = $global_ServiceDomain_back + 'api/CategoryEveryoneSearch';
  }
  return $url;
}

/*
 * 热门分类
 */
String getPopularClassificationList() {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/PopularClassification';
  } else {
    $url = $global_ServiceDomain_back + 'api/PopularClassification';
  }
  return $url;
}

/*
 * 漫画分类列表
 */
String getComicBookList() {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/ComicsList';
  } else {
    $url = $global_ServiceDomain_back + 'api/ComicsList';
  }
  return $url;
}

/*
 * 个人 基本信息
 */
String getUserProfile() {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/User/Profile';
  } else {
    $url = $global_ServiceDomain_back + 'api/User/Profile';
  }
  return $url;
}

/*
 * 个人 我的收藏
 */
String getUserFavourite() {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/User/Favourite';
  } else {
    $url = $global_ServiceDomain_back + 'api/User/Favourite';
  }
  return $url;
}

/*
 * 获取漫画详细信息
 */
String getComicsInfo(String $comicsId) {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/ComicsInfo?id=' + $comicsId;
  } else {
    $url = $global_ServiceDomain_back + 'api/ComicsInfo?id=' + $comicsId;
  }
  return $url;
}

/*
 * 获取漫画详细信息 - 章节
 */
String getAllChapter(String $comicsId, {int page = 1}) {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me +
        'api/ComicsAllChapter?id=' +
        $comicsId +
        '&page=$page';
  } else {
    $url = $global_ServiceDomain_back +
        'api/ComicsAllChapter?id=' +
        $comicsId +
        '&page=$page';
  }
  return $url;
}

/*
 * 获取漫画详细信息 - 大家都在看
 */
String getRecommendation(String $comicsId) {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/Recommendation?book_id=' + $comicsId;
  } else {
    $url =
        $global_ServiceDomain_back + 'api/Recommendation?book_id=' + $comicsId;
  }
  return $url;
}

/*
 * 获取漫画详细信息 - 里面漫画的所有图片
 */
String getComicsInfoEpisodes(String bookId, String chapterId) {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me +
        'api/ComicsEpisodes?bookId=$bookId&chapterId=$chapterId';
  } else {
    $url = $global_ServiceDomain_me +
        'api/ComicsEpisodes?bookId=$bookId&chapterId=$chapterId';
  }
  return $url;
}

/*
 * 获取漫画的评论 有两种获取方式 获取漫画全部的评论不需要传入分卷id 或者获取某一卷的评论
 */
String getComment(String bookId, {String chapterId, int page = 1}) {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me +
        'api/Comment/GetComment?bookId=$bookId&subsectionId=$chapterId&page=$page';
  } else {
    $url = $global_ServiceDomain_me +
        'api/Comment/GetComment?bookId=$bookId&subsectionId=$chapterId&page=$page';
  }
  return $url;
}

/*
 * 获取评论的某一个子评论
 */
String getCommentSonComment(String commentId, {int page = 1}) {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me +
        'api/Comment/CommentSonComment?comment_id=$commentId&page=$page';
  } else {
    $url = $global_ServiceDomain_me +
        'api/Comment/CommentSonComment?comment_id=$commentId&page=$page';
  }
  return $url;
}

/*
 * 操作 漫画 喜欢或不喜欢
 */
String operationComicsLikeAndNoLike() {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/ComicsLike';
  } else {
    $url = $global_ServiceDomain_me + 'api/ComicsLike';
  }
  return $url;
}

/*
 * 操作 评论区 喜欢或不喜欢
 */
String operationCommentLikeAndNoLike(String commentId) {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me +
        'api/Comment/CommentLike?comment_id=$commentId';
  } else {
    $url = $global_ServiceDomain_me +
        'api/Comment/CommentLike?comment_id=$commentId';
  }
  return $url;
}

/*
 * 操作 评论区 发布评论
 */
String operationCommentSendComment() {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/Comment/SendComment';
  } else {
    $url = $global_ServiceDomain_me + 'api/Comment/SendComment';
  }
  return $url;
}

String getUserLogin() {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/UserLogin';
  } else {
    $url = $global_ServiceDomain_me + 'api/UserLogin';
  }
  return $url;
}

/*
 * 搜索
 */
String getSearch() {
  if ($serviceState == 0) {
    $url = $global_ServiceDomain_me + 'api/Comment/search';
  } else {
    $url = $global_ServiceDomain_back + 'api/Comment/search';
  }
  return $url;
}

//跳板
String springboard() {
  // return "http://111.beaa.xyz/?url=";
  return "";
}

/*
 * 时间戳转换
 */
String iSO_8601ToNewData(String data, bool extend, {bool supers = false}) {
  try {
    if (extend) {
      if (supers == true) {
        if (DateUtil.isToday(DateTime.parse(data).millisecondsSinceEpoch)) {
          //!判断是不是今天

          return "今天 " +
              DateUtil.formatDate(
                  DateTime.parse(data).add(new Duration(hours: 0)),
                  format: "HH:mm:ss");
        } else {
          return DateUtil.formatDate(
              DateTime.parse(data).add(new Duration(hours: 0)),
              format: "yyyy - MM - dd");
        }
        /* if( DateUtil.formatDate(
            DateTime.parse(data).add(new Duration(hours: 0)),
            format: "yyyy/MM/dd").isAtSameMomentAs()) */
      } else {
        return DateUtil.formatDate(
            DateTime.parse(data).add(new Duration(hours: 0)),
            format: "yyyy - MM - dd");
      }
    } else {
      if (DateUtil.isToday(DateTime.parse(data).millisecondsSinceEpoch)) {
        //!判断是不是今天
        return "今天 " +
            DateUtil.formatDate(
                DateTime.parse(data).add(new Duration(hours: 0)),
                format: "HH:mm:ss");
      } else {
        String time =
            DateTime.parse(data).add(new Duration(hours: 0)).toString();
        time = DateUtil.formatDateMs(DateUtil.getDateMsByTimeStr(time),
            format: DataFormats.full);
        return time;
      }
    }
  } catch (e) {
    return '正在获取';
  }
}

dynamic readToJson($fileName) async {
  var appDocDir = await getApplicationDocumentsDirectory();
  var path = appDocDir.path;
  var localFile = new File('$path/${$fileName}');

  String str = await localFile.readAsString();

  return str.toString();
// 写入 json 数据
  // 写入 json 数据
/*   writeJSON(obj) async {
    try {
      final file = await localFile(await localPath());
      return file.writeAsString('123');
    } catch (err) {
      print(err);
    }
  }
 */
  // writeJSON(downloadList);
}

dynamic writeToJson($fileName, $body) async {
  var appDocDir = await getApplicationDocumentsDirectory();
  var path = appDocDir.path;
  var localFile = new File('$path/${$fileName}');

  try {
    localFile.writeAsString($body);
    return true;
  } catch (err) {
    print(err);
  }

  // writeJSON(downloadList);
}

bool updateSetting(String updateFields, updateData) {
  int $return;
  dataBaseUpdate('UserSetting', {updateFields: updateData}, "id = ?", [1])
      .then((data) {
    $return = data;
  });
  try {
    settingSettingBodyContorllerState.currentState.updateView();
  } catch (e) {
    print(e);
  }
  return ($return == 1) ? true : false;
}

String imagesIsPath(comicsInfoListJson.Docs doc) {
  //解析图片地址
  var $imageUrl = springboard() + doc.media.fileServer + doc.media.path;
  return $imageUrl;
}

/*
 * @description: 计算获取请求头的方法
 * @param : 
 * @return: 
 * @name: 
 * @test: test font
 * @msg: 
 * @param {type} 
 */
Map<String, Object> getApiRequestHeadrs($requestFunction) {
  var $randStr = randomAlpha(32).toUpperCase(); //随机字符串
  var $time = 1592923179; //时间戳
  var $hashData = {
    "time": $time.toString(),
    "apiKey": $apiKey.toString(),
    "nonce": $randStr.toString(),
    "appPlatform": $appPlatform.toString(),
    "language": $acceptLanguage.toString(),
    "authorization": $tempUserToKen.toString(),
    "appVersion": $appVersion.toString(),
    "appBuildVersion": $appBuildVersion.toString(),
    "appUUID": $appUUID.toString(),
    "requestFunction": $requestFunction,
  };
  var hmacSha512 = new Hmac(
      //第一次hash
      sha512,
      utf8.encode($requestToVerifyEncryptionKey)); // HMAC-SHA256
  var signature = hmacSha512.convert(utf8.encode(jsonEncode($hashData)));

  hmacSha512 = new Hmac(
      //第二次hash
      sha512,
      utf8.encode($requestToVerifyEncryptionKeySha512)); // HMAC-SHA256
  signature = hmacSha512.convert(utf8.encode(signature.toString()));
  var $headrs = {
    "time": $time.toString(), //时间戳
    "api-key": $apiKey.toString(),
    "nonce": $randStr.toString(), //随机字符串
    "app-platform": $appPlatform.toString(),
    "accept": "application/json",
    "Accept-Language": $acceptLanguage.toString(),
    "Authorization": $tempUserToKen.toString(), //用户token
    "app-version": $appVersion.toString(),
    "app-build-version": $appBuildVersion.toString(), //软件编译版本
    "signature": signature.toString(),
    "app-uuid": $appUUID.toString(),
  };
  return $headrs;
}

requestErrorParsing($json, {$context}) {
  switch ($json['code']) {
    case "A-10001": //app需要更新
      return Navigator.of($context).push(
        PageRouteBuilder(
          pageBuilder: (context, _, __) => GlobalTipsExtend(
            body: $json["data"]["msg"],
            height: 500,
            logo: {'isLogo': true, 'logoSrc': 'images/Tisp/UnknownError.png'},
            expand: false,
            expButton: {
              "isExpButton": true,
              "expButtonSuccessName": '立即更新',
              "expButtonSuccessOntab": () async {
                await launch($json['data']["download_url"]);
                Navigator.pop(context);
              },
              "expButtonErrorName": '退出App',
              "expButtonErrorOntab": () async {
                exit(0);
              },
            },
          ),
          opaque: false,
        ),
      );
      break;
    case "0": //未知错误
      return Navigator.of($context).push(
        PageRouteBuilder(
          pageBuilder: (context, _, __) => GlobalTipsExtend(
            body: $json["error"],
            height: 500,
            logo: {'isLogo': true, 'logoSrc': 'images/Tisp/UnknownError.png'},
            expand: false,
            expButton: {
              "isExpButton": $json['panic'],
              "expButtonSuccessName": '退出App',
              "expButtonSuccessOntab": () async {
                await launch($json['data']["download_url"]);

                Navigator.pop(context);
              },
              "expButtonErrorName": '退出App',
              "expButtonErrorOntab": () async {
                if ($json['panic']) {
                  exit(0);
                } else {
                  Navigator.pop(context);
                }
              },
            },
          ),
          opaque: false,
        ),
      );
      break;
    default:
      return Navigator.of($context).push(
        PageRouteBuilder(
          pageBuilder: (context, _, __) => GlobalTipsExtend(
            body: $json["error"],
            height: 500,
            logo: {'isLogo': true, 'logoSrc': 'images/Tisp/UnknownError.png'},
            expand: false,
            expButton: {
              "isExpButton": $json['panic'],
              "expButtonSuccessName": '退出App',
              "expButtonSuccessOntab": () async {
                await launch($json['data']["download_url"]);

                Navigator.pop(context);
              },
              "expButtonErrorName": '退出App',
              "expButtonErrorOntab": () async {
                if ($json['panic']) {
                  exit(0);
                } else {
                  Navigator.pop(context);
                }
              },
            },
          ),
          opaque: false,
        ),
      );
      break;
  }
}

/*
 * @name: 显示一个loading的弹窗
 * @test: 显示一个loading的弹窗
 * @msg: 显示一个loading的弹窗
 * @param {BuildContext} context
 * @param {String} tips
 * @return {type} 
 */
loadingDialog(BuildContext context, String tips) {
  return showDialog(
    context: context,
    barrierDismissible: false,
    builder: (context) => Scaffold(
      backgroundColor: Color.fromRGBO(0, 0, 0, 0),
      body: Container(
        alignment: Alignment.center,
        child: Container(
          height: ScreenUtil().setHeight(450),
          child: Column(
            children: <Widget>[
              Container(
                child: Image.asset(
                  "images/Loading/loading.gif",
                  fit: BoxFit.contain,
                  alignment: Alignment.topCenter,
                  height: ScreenUtil().setHeight(350),
                ),
              ),
              Text(
                tips,
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(60),
                  color: Color(0xffffffff),
                ),
              ),
            ],
          ),
        ),
      ),
    ),
  );
}
